package mint2tcp;

import java.io.*;
import java.net.*;

public class TcpServer implements Runnable {
    private int port;
    private ServerSocket serverSocket;
    private Socket clientSocket;
    private MainController controller;
    private volatile boolean running = false;
    private BufferedReader in;
    private PrintWriter out;

    public TcpServer(int port) {
        this.port = port;
    }

    public void setController(MainController controller) {
        this.controller = controller;
    }

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(port);
            controller.appendResponse("服务端已启动，监听端口：" + port + "\n");
            controller.setStatus("状态：服务端已启动", "green");
            running = true;

            while (running) {
                clientSocket = serverSocket.accept();
                controller.appendResponse("客户端已连接: " + clientSocket.getInetAddress() + "\n");
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));
                out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"), true);

                String line;
                while (running && (line = in.readLine()) != null) {
                    controller.appendResponse("收到客户端: " + line + "\n");
                    out.println("服务端收到: " + line);
                    DataParser.DataPoint dataPoint = DataParser.parseData(line);
                    if (dataPoint != null) {
                        controller.addDataPoint(dataPoint);
                    }
                }

                if (clientSocket != null && !clientSocket.isClosed()) {
                    clientSocket.close();
                }
            }
        } catch (IOException e) {
            if (running) {
                controller.appendResponse("服务端错误: " + e.getMessage() + "\n");
                controller.setStatus("状态：未连接", "red");
            }
        } finally {
            stopServer();
        }
    }

    public void stopServer() {
        running = false;
        try {
            if (in != null) in.close();
            if (out != null) out.close();
            if (clientSocket != null && !clientSocket.isClosed()) clientSocket.close();
            if (serverSocket != null && !serverSocket.isClosed()) serverSocket.close();
            controller.appendResponse("服务端已关闭\n");
        } catch (IOException e) {
            controller.appendResponse("关闭服务端错误: " + e.getMessage() + "\n");
        }
    }
}